package cn.teaseed.OSC.oscin;

import cn.teaseed.comn.CorsParam;
import com.illposed.osc.OSCListener;
import com.illposed.osc.OSCPortIn;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.SocketException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class VRCListener {
    public OSCPortIn in = null;

    private final static Map<String, OSCListener> urlMap = new HashMap<>();

    @PostConstruct
    public void init() throws SocketException {
        in = new OSCPortIn(CorsParam.VRChatListenerPort);
        in.startListening();
    }

    /**
     * 注册一个新的监听器
     *
     * @param url      OSC监听地址
     * @param listener OSC监听对象处理
     */
    public void addListener(String url, OSCListener listener) {
        in.addListener(url, listener);
        urlMap.put(url, listener);
    }

    /**
     * 目前交互逻辑可以保证在程序重启之前 已存在的监听语言不会继续执行
     * <p>
     * com.illposed.osc 此包下的监听方式暂时不支持编辑已存在的监听者
     * <p>
     * 后期更换OSC可能会解决这个问题 暂时搁置
     */
    @Deprecated
    public void updateListener(String url, OSCListener listener) {
        try {
            if (urlMap.containsKey(url)) {
                in.stopListening();
                urlMap.put(url, listener);
                in = new OSCPortIn(CorsParam.VRChatListenerPort);
                urlMap.forEach((k, v) -> {
                    in.addListener(k, v);
                });
                in.startListening();
            } else {
                addListener(url, listener);
            }
        } catch (SocketException e) {
            log.error("重置OSC监听异常:[{}]", e.getMessage());
        }
    }

}
